var util = require('../../../utils/util.js');
var apiObject = require('../../../utils/api.js');
var app = getApp();
Page({

  data: {
    farmArray: ['农场一', '农场二', '农场三', '农场四'],
    farmIndex: 0,  //农场数组
    monitorPlan:[],
    isShowModal:false,  //显示选择农场弹窗
    planId:""
  },

  onLoad: function (e) {

  },
  onShow:function(e){
    var that= this;
    wx.removeStorageSync("plan");
    util.request(apiObject.api.getPlanList).then(function (res) {
      console.log(res)
      if (res.code == 200) {
        that.setData({
          monitorPlan: res.result.monitorPlan
        })
      } else {
        util.showModal(res.message);
      }
    })
  },
  redirectToSetPlan: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '../setPlan/index?id='+id,
    })
  },
  farmPickerChange: function (e) {
    this.setData({
      farmIndex: e.detail.value
    })
  },
  toggleModal: function (e) {
    var that=this;
    var id = e.currentTarget.dataset.id;
    util.request(apiObject.api.getSimpleFarmList).then(function (res) {
      console.log(res)
      if (res.code == 200) {
        that.setData({
          farmArray: res.result.farmList,
          isShowModal: !that.data.isShowModal,
          planId: typeof (id) != "undefined"?id:""
        })
      } else {
        util.showModal(res.message);
      }
    })
  },
  addPlan: function () {
    wx.navigateTo({
      url: '../addPlan/index',
    })
  },
  deletePlan:function(e){
    var that=this;
    var id=e.currentTarget.dataset.id;

    util.showModal("确定要删除该方案吗?",true).then(function(res){
      if(res.confirm){
        util.request(apiObject.api.deletePlan,{
          planId:id
        }).then(function (res) {
          console.log(res)
          if (res.code == 200) {
            that.onShow();
          } else {
            util.showModal(res.message);
          }
        })
      }
    });
  },
  submit:function(){
    var that = this;
    console.log(this.data.planId);
    console.log(this.data.farmArray[this.data.farmIndex])

    util.request(apiObject.api.syncFarm,{
      planId: that.data.planId,
      farmId: that.data.farmArray[that.data.farmIndex].id
    }).then(function (res) {
      if (res.code == 200) {
        util.showModal("应用成功").then(function(){
          wx.navigateBack()
        });
      } else {
        util.showModal(res.message);
      }
    })
  }
})